<?php

class AdminUserController extends AdminController
{
  use ApiTrait;
  public $allows = ['login', 'logout'];
  public static function __permissions()
  {
    return [
      'name' => '账号权限',
      'permissions' => [
        'admin.list' => '查看管理账号列表',
        'admin.edit' => '新增管理／编辑管理人员',
        'role.list' => [ 'name' => '角色权限', 'desc' => '查看角色列表'],
        'role.edit' => [ 'name' => '角色权限', 'desc' => '新增/编辑角色权限'],
      ],
    ];
  }

  public function loginAction()
  {
    if ($this->isLogin()) {
      $this->res->gotoUrl('admin');
    }
    if ($this->req->isPost()) {
     $username = $this->req->getPost('username');
     $password = $this->req->getPost('password');
     $code = $this->req->getPost('code');
     if (hasEmpty([$username, $password, $code])) {
       $this->addErrorMessage('参数错误');
       $this->res->reload();
     }
     if (!$this->getModel('captcha')->checkCode('admin/user/login', $code)) {
       $this->addErrorMessage('验证码错误');
       $this->res->reload();
     }
     $user = $this->getModel('user')->auth($username, $password);
     if (!$user || !$user->login()) {
       $this->addErrorMessage('用户密码错误！！');
       $this->res->reload();
     }
     $this->res->gotoUrl('admin');
    }
    $view = $this->getView();
    $view->display('admin/user/login.phtml');
  }

  public function logoutAction()
  {
    session_destroy();
    $this->res->gotoUrl('admin/user/login');
  }

  public function roleAction($roleid = '')
  {
    $view = $this->getView();
    $userModel = $this->getModel('user');
    //新增角色
    if ($roleid === 'add') {
      if (!$this->account->checkPermission(['role.edit'])) {
        $this->addErrorMessage('您未拥有相应权限！！');
        $this->gotoUrl('admin', true);
      }
      if ($this->req->isPost()) {
        $rolename = $this->req->getPost('rolename', '');
        $permissions = $this->req->getPost('permissions', []);
        if (hasEmpty([$rolename, $permissions]) || !is_array($permissions)) {
          $this->addErrorMessage('参数错误！！');
          $this->res->reload();
        }
        $status = Role::IS_EFFECTIVE == $this->req->getPost('status') ?
          Role::IS_EFFECTIVE : Role::IS_FORBIDDEN;
        $role = $userModel->createRole([
          'rolename' => $rolename, 'status' => $status
        ]);
        if ($role) {
          $role->setPermissions($permissions);
          $this->addSuccessMessage('成功新增角色[' . $role->rolename . ']');
        } else {
          $this->addErrorMessage('操作失败请重试');
        }
        $this->res->gotoUrl('admin/user/role');
      }
      $view->assign('permissions', $userModel->getPermissions());
      $view->display('admin/user/role_edit.phtml');
    //修改角色
    } else if (!empty($roleid) && ($role = $userModel->getRole($roleid))) {
      if (!$this->account->checkPermission(['role.edit'])) {
        $this->addErrorMessage('您未拥有相应权限！！');
        $this->gotoUrl('admin', true);
      }
      if ($this->req->isPost()) {
        $permissions = $this->req->getPost('permissions');
        if (!is_array($permissions)) {
          $this->addErrorMessage('参数错误');
        } else {
          $role->rolename = empty($this->req->getPost('rolename')) ?
            $role->rolename : $this->req->getPost('rolename');
          $role->status = Role::IS_EFFECTIVE == $this->req->getPost('status') ?
            Role::IS_EFFECTIVE : Role::IS_FORBIDDEN;
          $role->setPermissions($permissions);
          $role->update();
          $this->addSuccessMessage('保存成功');
        }
        $this->res->reload();
      }
      $view->assign([
        'role' => $role,
        'permissions' => $userModel->getPermissions()
      ]);
      $view->display('admin/user/role_edit.phtml');
    } else {
      if (!$this->account->checkPermission(['role.list', 'admin.edit', 'admin.list'], 'or')) {
        $this->addErrorMessage('您未拥有相应权限！！');
        $this->gotoUrl('admin', true);
      }
      //查看角色列表
      $rows = 15;
      $page = max(intval($this->req->getQuery('page', 1)), 1);
      $query = [
        'search' => trim($this->req->getQuery('search', '')),
        'status' => $this->req->getQuery('status', '')
      ];
      $rolesList = $userModel->getRolesList($query, $page, $rows);
      if ($this->req->isAjax()) {
        return $this->okReturn([
          'roles' => $rolesList,
          'next' => count($rolesList) == $rows ,
        ]);
      }
      $view->assign([
        'rolesList' => $rolesList,
        'count' => $userModel->getRolesCount($query),
        'page' => $page, 'rows' => $rows, 'query' => $query
      ]);
      $view->display('admin/user/role.phtml');
    }
  }

  public function roleAjaxAction()
  {
    if (!$this->req->isPost() || !$this->req->isPost()) {
      return $this->errorReturn('参数错误');
    }
    if (!$this->account->checkPermission(['role.edit'])) {
      return $this->errorReturn('您未拥有相应权限！！');
    }
    $userModel = $this->getModel('user');
    if ($this->req->getPost('type') === 'batch') {
      $roleids = $this->req->getPost('roleids');
      if (empty($roleids) || !is_array($roleids)) {
        return $this->errorReturn('参数错误');
      }
      $status = $this->req->getPost('op') === 'forbidden' ?
        Role::IS_FORBIDDEN : Role::IS_EFFECTIVE;
      return $this->okReturn([
        'affected' => $userModel->batchUpdateRolesStatus($roleids, $status)
      ]);
    } else {
      $role = $userModel->getRole($this->req->getPost('roleid', '0'));
      if ($role) {
        $role->status = $this->req->getPost('op') === 'forbidden' ?
          Role::IS_FORBIDDEN : Role::IS_EFFECTIVE;
        $affected = $role->update();
        return $this->okReturn(['affected' => $affected]);
      }
      return $this->errorReturn('角色不存在！！');
    }
  }

  public function indexAction()
  {
    if (!$this->account->checkPermission(['admin.list'])) {
      $this->addErrorMessage('您未拥有相应权限！！');
      $this->gotoUrl('admin', true);
    }
    $view = $this->getView();
    $userModel = $this->getModel('user');
    $rows = 15;
    $page = max(intval($this->req->getQuery('page', 1)), 1);

    $query = [
      'search' => trim($this->req->getQuery('search', '')),
      'status' => trim($this->req->getQuery('status', '')),
    ];
    $role = $userModel->getRole(intval($this->req->getQuery('roleid', '')));
    if ($role) {
      $query['role'] = $role->role_id;
    }
    $view->assign([
      'usersList' => $userModel->getUsersList($query, $page, $rows),
      'count' => $userModel->getUsersCount($query, $page, $rows),
      'page' => $page, 'rows' => $rows, 'query' => $query,
      'role' => $role
    ]);
    $view->display('admin/user/user.phtml');
  }

  public function addAction()
  {
    //新增用户
    if (!$this->account->checkPermission(['admin.edit'])) {
      $this->addErrorMessage('您未拥有相应权限！！');
      $this->gotoUrl('admin', true);
    }
    if ($this->req->isPost()) {
      $username = $this->req->getPostTrim('username');
      $nickname = $this->req->getPostTrim('nickname');
      $password = $this->req->getPostTrim('password');
      $avatar = $this->req->getPostTrim('avatar');
      $roleid = $this->req->getPostTrim('roleid');
      $userModel = $this->getModel('user');
      if (hasEmpty([$username, $password, $roleid, $avatar]) || !is_numeric($roleid) || !($role = $userModel->getRole($roleid))) {
        $this->addErrorMessage('参数错误！！');
        $this->res->reload();
      }
      $this->getSession()->set('addUser', [
        'data' => $this->req->getPost(),
        'role' => [
          'role_id' => $role->role_id,
          'rolename' => $role->rolename
        ]
      ]);
      //检测用户名是否存在
      if (!$userModel->getUser($username, 'users.username')) {
        $from = [
          'username' => $username,
          'nickname' => empty($nickname) ? $username : $nickname,
          'password' => $password,
          'avatar' => $avatar,
          'role_id' => $roleid,
          'status' => $this->req->getPostTrim('status', '') == User::IS_EFFECTIVE ?
            User::IS_EFFECTIVE : User::IS_FORBIDDEN ,
        ];
        if ($userModel->createUser($from)) {
          $this->addSuccessMessage('创建用户[ ' . $username . ' ]成功');
          $this->getSession()->set('addUser', null);
          $this->res->gotoUrl('admin/user');
        } else {
          $this->addErrorMessage('创建用户[ ' . $username . ' ]失败，请重试');
        }
      } else {
        $this->addErrorMessage('[ ' . $username . ' ] 帐号已存在,请更换帐号再试');
      }
      $this->res->reload();
    }
    $view = $this->getView();
    $view->display('admin/user/user_add.phtml');
  }

  public function editAction($uid = '')
  {
    if (!$this->account->checkPermission(['admin.edit'])) {
      $this->addErrorMessage('您未拥有相应权限！！');
      $this->gotoUrl('admin', true);
    }
    $userModel = $this->getModel('user');
    if (!is_numeric($uid) || !($user = $userModel->getUser($uid))) {
      $this->addErrorMessage('用户不存在！！');
      $this->res->gotoUrl('admin/user');
    }
    $user = $userModel->getUser($uid);
    if ($this->req->isPost()) {
      $nickname = $this->req->getPostTrim('nickname');
      $password = $this->req->getPostTrim('password');
      $avatar = $this->req->getPostTrim('avatar');
      $roleid = $this->req->getPostTrim('roleid');
      $editUser = ['data' => $this->req->getPost()];
      do {
        $userModel = $this->getModel('user');
        if (hasEmpty([$roleid, $avatar]) || !is_numeric($roleid) || !($role = $userModel->getRole($roleid))) {
          $this->addErrorMessage('参数错误！！');
          break;
        }
        $editUser['role'] = ['role_id' => $role->role_id, 'rolename' => $role->rolename];
        $user->status = $this->req->getPostTrim('status', '') == User::IS_EFFECTIVE ?
          User::IS_EFFECTIVE : User::IS_FORBIDDEN;
        $user->avatar = $avatar;
        $user->role_id = $roleid;
        if (!empty($password)) {$user->setPassword($password);}
        if (!empty($nickname)) {$user->nickname = $nickname;}
        $user->update();
        $editUser = null;
        $this->addSuccessMessage('更新用户[ '. $user->username .  ' ]资料成功！！');
      } while(0);
      $this->getSession()->set('editUser', $editUser);
      $this->res->reload();
    }
    $role = $user->getRole();
    $view = $this->getView();
    $view->assign([
      'user' => $user,
      'role' => ['role_id' => $role->role_id, 'rolename' => $role->rolename]
    ]);
    $view->display('admin/user/user_edit.phtml');
  }

  public function infoAction()
  {
    $userModel = $this->getModel('user');
    $user = $this->account;
    if ($this->req->isPost()) {
      $nickname = $this->req->getPostTrim('nickname');
      $password = $this->req->getPostTrim('password');
      $avatar = $this->req->getPostTrim('avatar');
      $infoUser = ['data' => $this->req->getPost()];
      do {
        $userModel = $this->getModel('user');
        if (hasEmpty([$avatar])) {
          $this->addErrorMessage('参数错误！！');
          break;
        }
        $user->avatar = $avatar;
        if (!empty($password)) {$user->setPassword($password);}
        if (!empty($nickname)) {$user->nickname = $nickname;}
        $user->update();
        $infoUser = null;
        $this->addSuccessMessage('修改个人资料成功！！');
      } while(0);
      $this->getSession()->set('infoUser', $infoUser);
      $this->res->reload();
    }
    $role = $user->getRole();
    $view = $this->getView();
    $view->assign([
      'user' => $user,
    ]);
    $view->display('admin/user/user_info.phtml');
  }

  public function updateAjaxAction()
  {
    if (!$this->req->isAjax() || !$this->req->isPost()) {
      return $this->errorReturn('参数错误');
    }
    if (!$this->account->checkPermission(['admin.edit'])) {
      return $this->errorReturn('您未拥有相应权限！！');
    }
    $userModel = $this->getModel('user');
    $action = $this->req->getPost('type');
    if ($action === 'batch') {
      $userids = $this->req->getPost('userids');
      if (empty($userids) || !is_array($userids)) {
        return $this->errorReturn('参数错误');
      }
      $status = $this->req->getPost('op') === 'forbidden' ?
        User::IS_FORBIDDEN : User::IS_EFFECTIVE;
      return $this->okReturn([
        'affected' => $userModel->batchUpdateUsersStatus($userids, $status)
      ]);
    } else if ($action === 'resetpassword') {
      $user = $userModel->getUser($this->req->getPost('userid', '0'));
      if ($user) {
        $newPassword = randomString(6);
        $user->setPassword($newPassword);
        $user->update();
        return $this->okReturn('用户[ ' . $user->username . ' ] 新密码为[ ' . $newPassword . ' ]');
      }
      return $this->errorReturn('用户不存在！！');
    } else {
      $user = $userModel->getUser($this->req->getPost('userid', '0'));
      if ($user) {
        $user->status = $this->req->getPost('op') === 'forbidden' ?
          User::IS_FORBIDDEN : User::IS_EFFECTIVE;
        return $this->okReturn(['affected' => $user->update()]);
      }
      return $this->errorReturn('用户不存在！！');
    }

  }

}